<?php

namespace app\admin\services;

use app\admin\model\CustomerModel;
use app\admin\model\ExpressPushJdModel;
use app\admin\model\OrderInModel;
use app\client\services\JDService;
use app\client\services\TiktokPromoteService;
use think\facade\Db;
use think\facade\Validate;

class ExpressOrderService extends BaseService
{
    /**
     * 京东物流信息推送接收
     * @return void
     */
    public static function pushJD($p){
        $rule=[
            'operationTitle'=>'require',
            'category'=>'require',
            'categoryName'=>'require',
            'state'=>'require',
            'waybillCode'=>'require',
            'orderId'=>'require',
            'operationTime'=>'require',
            'operationRemark'=>'require',
            'operateSiteId'=>'require'
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p)){
            api_return(500,$validate->getError());
        }
        if(!$orderInfo=OrderInModel::where([['orderid','=',$p['orderId']]])->find()){
            api_return(500,'订单不存在');
        }
        Db::startTrans();
        $status=config('orderStatusMap')['jdCode2Status'][$p['state']];
        //订单已完成，更新实际重量，给客户分配余额
        if($status==4&&$orderInfo['status']!=$status){
            $res=JDService::GetActualFeeInfo($p['waybillCode']);
            $orderInfo['realweight']=$res['data']['actualOrderWeight'];
            $orderInfo['total_amount']=$orderInfo['realweight']*config('unitPrice')['cloth'];
            CustomerModel::setBalance($orderInfo['customer_id'],$orderInfo['total_amount'],1,$orderInfo['id']);
            $orderInfo['promote_res']=self::promoteCount($orderInfo['customer_id'],$orderInfo['orderid'],$orderInfo['realweight'],$orderInfo['create_time']);
        }
        $orderInfo['status']=$status;
        $r1=$orderInfo->save();
        $r2=ExpressPushJdModel::editWithReturn($p);
        if($r1&&$r2) {
            Db::commit();
            api_return(200 );
        }else{
            Db::rollback();
            api_return(500);
        }

    }

    /**
     * 推广订单结算
     * @param $customerId
     * @param $orderNo
     * @param $realWeight
     * @param $create_time
     * @return mixed|\stdClass
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function promoteCount($customerId,$orderNo,$realWeight,$create_time){
        $customerInfo=CustomerModel::find($customerId);
        if($customerInfo->sharecode) {
            switch ($customerInfo->platform){
                case 'dy':
                    $res=TiktokPromoteService::pushOrder($customerInfo->sharecode, $orderNo, $realWeight, $create_time);
                    break;
                default:
                    $res = new \stdClass();
            }
            return  $res;
        }else{
            return new \stdClass();
        }
    }
}
